package cn.itcast.controller.cargo;

import cn.itcast.base.BaseController;
import cn.itcast.domain.cargo.ContractProduct;
import cn.itcast.domain.cargo.ContractProductExample;
import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryExample;
import cn.itcast.service.ContractProductService;
import cn.itcast.service.FactoryService;
import cn.itcast.utils.FileUploadUtil;
import cn.itcast.utils.UtilFuns;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.List;

@Controller
@RequestMapping("/cargo/contractProduct")
public class ContractProductController extends BaseController {

    @Reference
    private ContractProductService contractProductService;
    @Reference
    private FactoryService factoryService;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    @RequestMapping(name = "pageHelper插件分页查询合同下货物",value = "/list")
    public String findAll(String contractId,@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "5") int pageSize){

        //根据合同的id查询出这个合同下的所有货物
        ContractProductExample contractProductExample = new ContractProductExample();
        ContractProductExample.Criteria criteria = contractProductExample.createCriteria();
        criteria.andContractIdEqualTo(contractId);
        PageInfo pb = contractProductService.findAll(contractProductExample, pageNum, pageSize);
        request.setAttribute("pb",pb);

        //带着生产货物的生产商过去页面展示
        FactoryExample factoryExample = new FactoryExample();
        FactoryExample.Criteria criteria1 = factoryExample.createCriteria();
        criteria1.andCtypeEqualTo("货物");
        List<Factory> list = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",list);

        request.setAttribute("contractId",contractId);
        return "cargo/product/product-list";
    }



    @RequestMapping(name = "合同货物的新增",value = "/edit")
    //只要使用springmvc做上传就得使用其提供的核心上传对象：MultipartFile
                    // 使用条件一：MultipartFile的参数名要和页面file标签的name名一致
                    // 使用条件二：在springmvc的配置文件中配置该核心对象
                                    //    String fileName = productPhoto.getOriginalFilename(); 图片名称
                                    //        InputStream is = productPhoto.getInputStream(); 图片内容
    public String edit(ContractProduct contractProduct, MultipartFile productPhoto) throws Exception {



        contractProduct.setCompanyId(company_id);
        contractProduct.setCompanyName(company_name);
        if(UtilFuns.isEmpty(contractProduct.getId())){

            // 保存图片到七牛云
            String imgSrc = fileUploadUtil.upload(productPhoto);
            contractProduct.setProductImage("http://"+imgSrc);
            System.out.println(imgSrc);
            //保存数据到数据库
            contractProductService.save(contractProduct);
        }else {
            //修改
            contractProductService.update(contractProduct);
        }

        // 带着合同号 查询最新数据
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractProduct.getContractId();
    }




    @RequestMapping(name = "到货物的修改页面",value = "/toUpdate")
    public String toView(String id){

        //获取货物的对象
        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct",contractProduct);

        //货物的生产厂家
        FactoryExample factoryExample = new FactoryExample();
        FactoryExample.Criteria criteria1 = factoryExample.createCriteria();
        criteria1.andCtypeEqualTo("货物");
        List<Factory> list = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",list);
        return "cargo/product/product-update";
    }


    @RequestMapping(name = "删除货物",value = "/delete")
    public String delete(String id,String contractId){

        //删除
        contractProductService.delete(id);

        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }


    @RequestMapping(name = "到上传货物的页面",value = "/toImport")
    public String toImport(String contractId){

        request.setAttribute("contractId",contractId);
        //到上传页面
        return "cargo/product/product-import";
    }


    @RequestMapping(name = "到上传货物的页面",value = "/import")
    //contractId: 获取货物的合同号
    public String imports(String contractId,MultipartFile file) throws Exception {
        // 整理货物的数据
                //excel表中
                        // 导入依赖
                        // 读取上传的excel表数据封装到货物对象中
                                    //new XSSFWorkbook(); 创建excel
                                    //new XSSFWorkbook(Stirng path); 磁盘上的excel
                                    //new XSSFWorkbook(file.getInputStream()); 读取上传你的文件流
        Workbook wb=new XSSFWorkbook(file.getInputStream());
        Sheet st = wb.getSheetAt(0);
        int RowNum = st.getLastRowNum(); //3行 返回角标2
        for(int i=1;i<RowNum+1;i++){
             //获取每一行
            Row row = st.getRow(i);
            // 有一行就得有一个数组
            Object[] arr=new Object[row.getLastCellNum()];   //arr[10]

            // 获取每一行的列数
            for(int j=1;j<row.getLastCellNum();j++){
                // 获取每一个单元格
                Cell cell = row.getCell(j);
                // 判断单元格类型获取单元格数据
                Object obj = getCellValue(cell); //每一个单元格的内容
                arr[j]=obj; //arr[1]=升华  arr[2]=xx001 ..
            }

            //将数组的内容给对象
            ContractProduct contractProduct = new ContractProduct(arr,company_id,company_name);
            contractProduct.setContractId(contractId);
            //调用service
            contractProductService.save(contractProduct);
        }

        //到上传页面
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }


    private Object getCellValue(Cell cell) {

        Object obj=null;
        //判断单元格类型
        CellType cellType = cell.getCellType();
        switch (cellType){
            case STRING:
                obj=cell.getStringCellValue();
                break;
            case BOOLEAN:
                obj= cell.getBooleanCellValue();
                break;
            case NUMERIC:
                boolean flg = DateUtil.isCellDateFormatted(cell);
                if(flg){
                    //日期类型
                    obj=cell.getDateCellValue();
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    obj=format.format(obj);
                }else{
                    obj=cell.getNumericCellValue();
                }
        }
        return obj;
    }



}
